package com.stox.manager;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.stereotype.Component;

import com.stox.event.NewExchangeEvent;
import com.stox.event.NewScripEvent;
import com.stox.model.Exchange;
import com.stox.model.Scrip;
import com.stox.repository.ScripRepository;

@Component
public class ScripManager implements SmartApplicationListener {

	@Autowired
	private ScripRepository scripRepository;
	
	public int getOrder() {
		return 2;
	}
	
	public void onApplicationEvent(ApplicationEvent event) {
		if(NewScripEvent.class.isAssignableFrom(event.getClass())){
			//save((Scrip)event.getSource());
		}else if(NewExchangeEvent.class.isAssignableFrom(event.getClass())){
			Exchange exchange = (Exchange)event.getSource();
			scripRepository.createPartition(exchange.getCode());
		}
	}
	
	public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
		return NewScripEvent.class.isAssignableFrom(eventType) ||
				NewExchangeEvent.class.isAssignableFrom(eventType);
	}
	
	public boolean supportsSourceType(Class<?> sourceType) {
		return Scrip.class.isAssignableFrom(sourceType) ||
				Exchange.class.isAssignableFrom(sourceType);
	}
	
	public Scrip findOne(String scripCode){
		return scripRepository.findOne(scripCode);
	}
	
	public List<Scrip> findByExchangeCode(String exchangeCode){
		return scripRepository.findByExchangeCode(exchangeCode);
	}
	
	private Scrip save(Scrip scrip){
		return scripRepository.save(scrip);
	}
}
